﻿using GenericHostDemo.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GenericHostDemo
{
    /// <summary>
    /// 主机构建器
    /// </summary>
    public class HostBuilder
    {
        private readonly ServiceCollection _services = new ServiceCollection();
        private Action<IServiceCollection> _configureServices;
        public HostBuilder ConfigureServices(Action<IServiceCollection> configureServices)
        {
            _configureServices = configureServices;
            return this;
        }
        public IHost Build()
        {
            // 执行服务配置
            _configureServices?.Invoke(_services);

            // 构建服务容器
            IServiceProvider? serviceProvider = _services.BuildServiceProvider();

            // 查找所有后台服务
            var hostedServices = _services.GetServices()
                .Where(s => typeof(IHostedService).IsAssignableFrom(s.Key))
                .Select(s => (IHostedService)s.Value)
                .ToList();
            return new Host(serviceProvider, hostedServices);
        }
    }

    class Host : IHost
    {
        private readonly List<IHostedService> _hostedServices;

        public IServiceProvider Services { get; }

        public Host(IServiceProvider serviceProvider, List<IHostedService> hostedServices)
        {
            Services = serviceProvider;
            _hostedServices = hostedServices;
        }
        public async Task StartAsync()
        {
            foreach (var service in _hostedServices)
            {
                await service.StartAsync();
            }
        }
        public async Task StopAsync()
        {
            foreach (var service in _hostedServices)
            {
                await service.StopAsync();
            }
        }
        public void Dispose() => StopAsync().Wait();
    }
}
